package com.service.weChatWifiLogin.utile;

import com.service.config.utils.DateUtils;
import com.service.config.utils.FileUtils;
import com.service.config.utils.StringUtils;
import com.service.config.utils.ToolUtil;
import com.service.weChatWifiLogin.entity.VFilePhysicsInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Random;

/** @Author: wangqieyu @Description: MD5加解密工具类 @Date: 2020/10/27 14:58 */
public class MD5Util {
  private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7",
          "8", "9", "a", "b", "c", "d", "e", "f"};
  private static final String HexStr = "0123456789abcdef";
  /**
   * 转换字节数组为16进制字串
   * @param b 字节数组
   * @return 16进制字串
   */
  public static String byteArrayToHexString(byte[] b) {
    StringBuilder resultSb = new StringBuilder();
    for (byte aB : b) {
      resultSb.append(byteToHexString(aB));
    }
    return resultSb.toString();
  }
  public static byte[] hexToByteArr(String hexStr) {
    char[] charArr = hexStr.toCharArray();
    byte btArr[] = new byte[charArr.length / 2];
    int index = 0;
    for (int i = 0; i < charArr.length; i++) {
      int highBit = HexStr.indexOf(charArr[i]);
      int lowBit = HexStr.indexOf(charArr[++i]);
      btArr[index] = (byte) (highBit << 4 | lowBit);
      index++;
    }
    return btArr;
  }
  /**
   * 转换byte到16进制
   * @param b 要转换的byte
   * @return 16进制格式
   */
  private static String byteToHexString(byte b) {
    int n = b;
    if (n < 0) {
      n = 256 + n;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return hexDigits[d1] + hexDigits[d2];
  }

  /**
   * MD5编码
   * @param origin 原始字符串
   * @return 经过MD5加密之后的结果
   */
  public static String MD5Encode(String origin) {
    String resultString = null;
    try {
      resultString = origin;
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(resultString.getBytes(StandardCharsets.UTF_8));
      resultString = byteArrayToHexString(md.digest());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return resultString;
  }

  /**
   * 随机密码生成器
   * @param length
   * @return
   */
  public static String getCharAndNumr(int length) {
    StringBuffer val = new StringBuffer();
    Random random = new Random();
    for (int i = 0; i < length; i++) {
      // 输出字母还是数字
      String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
      // 字符串
      if ("char".equalsIgnoreCase(charOrNum)) {
        // 取得大写字母还是小写字母
        int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
        val .append((char) (choice + random.nextInt(26)));
      } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
        val .append(String.valueOf(random.nextInt(10)));
      }
    }
    System.out.println(val.toString());
    return val.toString();
  }
  /**
   * 下载
   * @param response
   * @param request
   * @param fileName
   */
  public static void downloadFile(HttpServletResponse response, HttpServletRequest request, String fileName) {
    try {
      if (!FileUtils.isValidFilename(fileName)) {
        throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
      }
      String realFileName = DateUtils.dateTimeNow() + fileName.substring(fileName.indexOf("_") + 1);
      String filePath = ToolUtil.getDownloadPath() + fileName;
      response.setCharacterEncoding("utf-8");
      response.setContentType("application/octet-stream");
      response.setHeader("Content-Disposition",
              "attachment;filename=" + FileUtils.setFileDownloadHeader(request, realFileName));
      FileUtils.writeBytes(filePath, response.getOutputStream());
      FileUtils.deleteFile(filePath);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
  public static String getUrl(VFilePhysicsInfo vFilePhysicsInfo) {
    return vFilePhysicsInfo.getFileseverdomain().concat(vFilePhysicsInfo.getFiledicdomain()).concat("/").concat(vFilePhysicsInfo.getFilename());
  }
  public static void main(String[] args) {
    getCharAndNumr(5);
  }
}
